package com.example.lotterybackend.service.impl;

import com.example.lotterybackend.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterybackend.common.exception.ServiceException;
import com.example.lotterybackend.common.utils.CaptchaUtil;
import com.example.lotterybackend.common.utils.JacksonUtil;
import com.example.lotterybackend.common.utils.RedisUtil;
import com.example.lotterybackend.common.utils.RegexUtil;
import com.example.lotterybackend.common.utils.SmsUtil;
import com.example.lotterybackend.service.VerificationCodeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 验证码服务实现类
 * @author ricejson
 */
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    private static final String VERIFICATION_CODE_PREFIX = "RICE:VERIFY:";
    private static final Long VERIFICATION_CODE_EXPIRATION = 60L;
    @Resource
    private SmsUtil smsUtil;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean sendVerifyCode(String phoneNumber) {
        // 1. 验证电话号码格式
        if (!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.USER_VERIFY_PHONE_ERROR);
        }
        // 2. 构造随机验证码
        String captcha = CaptchaUtil.randomNNumbers(4);
        // 3. 发送短信
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", captcha);
        String templateParam = JacksonUtil.writeValueAsString(paramMap);
        try {
            smsUtil.sendMessage(phoneNumber, "SMS_474175316", templateParam);
        } catch (Exception e) {
            throw new ServiceException(ServiceErrorCodeConstants.USER_VERIFY_SEND_ERROR);
        }
        // 4. 缓存验证码到redis中
        redisUtil.set(VERIFICATION_CODE_PREFIX + phoneNumber, captcha, VERIFICATION_CODE_EXPIRATION);
        return true;
    }

    @Override
    public String getVerifyCode(String phoneNumber) {
        // 1. 校验电话号码格式
        if (!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.USER_VERIFY_PHONE_ERROR);
        }
        // 2. 从redis中取出验证码
        return redisUtil.get(VERIFICATION_CODE_PREFIX + phoneNumber);
    }
}
